package dao;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;

import util.Convert;

public class SequenceDAO implements Serializable{
	
	private MySqlConnecte myConn = new  MySqlConnecte();
	
	public short createTouriste(String name, Date in, Date out)
	{
		try
		{
			final String query = "insert into TOURISTE (NOM,DATEIN,DATEOUT) values (?,?,?)";
			PreparedStatement preparedQuery = this.myConn.getConnection().prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
			preparedQuery.setString(1, name);
			preparedQuery.setDate(2, Convert.dateToSQL(in));
			preparedQuery.setDate(3, Convert.dateToSQL(out));
			final ResultSet res=preparedQuery.executeUpdate();
			//final ResultSet res = preparedQuery.getGeneratedKeys();
			res.first();
			return (short)res.getInt(1);
		}
		catch(Exception e)
		{
			e.printStackTrace(System.err);
			return -1;
		}
	}
	
	//Cherche max NumTouristNumberCard
	public short maxTouristNumber(){
		try{
			String sqlCommand=("SELECT max(numTourist) FROM sequenceVisite");
			ResultSet rs = myConn.getList(sqlCommand);
			short maxNT=0;
			if (rs.next()){
				maxNT=rs.getShort(1);
			}
			return maxNT;
		
		} catch(Exception e) {
			e.printStackTrace();
			return -1;
		}
		
	}
	
	
	//ajouter nouveau Tourist avec SequenceVisite vide
	public boolean addSequence(short numeroCardTourist, String nomTourist){
		try{
			String sqlCommand = "INSERT INTO SequenceVisite(numTourist,nomTourist,Sequence) VALUES("+numeroCardTourist+",'"+nomTourist+"','')";
			return myConn.updateList(sqlCommand);
		} catch(Exception e) {
			System.out.println(""+nomTourist+ " can not be added to list of tourist");
			e.printStackTrace();
			return false;
		}
	}
	
	//update sequence visite d'un tourist quand il commence � visiter un site
	public boolean updateSequence(short numTourist, String nomSite){
		try{	
			String sqlCommand = "UPDATE SequenceVisite SET Sequence = CONCAT(Sequence,' "+nomSite+"') WHERE numTourist="+numTourist+"";
			return myConn.updateList(sqlCommand);
		} catch(Exception e) {
			System.out.println("Sequence of tourist n� "+numTourist+ " can not be modified");
			e.printStackTrace();
			return false;
		}
	}
	
	//get nomTourist 
	public String getNomTourist(short numTourist){
		try{
			String sqlCommand=("SELECT nomTourist FROM sequenceVisite WHERE numTourist="+numTourist+"");
			ResultSet rs = myConn.getList(sqlCommand);
			String nomT=null;
			if (rs.next()){
				nomT=rs.getString(1);
			}
			return nomT;
		
		} catch(Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	
}
